package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.CatalogVO;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.awt.event.ItemEvent;
import java.util.*;

@Service
//@Transactional //事务最后处理
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IStrategyService strategyService;


    @Override
    public StrategyCatalog get(String id) {
        Optional<StrategyCatalog> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<StrategyCatalog> query(QueryObject qo) {
        //List<StrategyCatalog> list = repository.findAll(); //使用repostory对象查询的结果不满足带条件查询
        //使用MongoTemplate，可以满足条件查询，但是返回的是list集合，如何封装成Page对象？
        Query query = new Query();
        //PageImpl构造器的参数3：total
        long total = template.count(query, StrategyCatalog.class);

        if (total == 0) {
            //总条数为0 就返回空的page回去
            return Page.empty();
        }
        //PageImpl构造器的参数2：pageable
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        query.with(pageable);
        //PageImpl构造器的参数1：list
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        return new PageImpl<StrategyCatalog>(list, pageable, total);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {

        //目的地的name是null，倒是前台传了destId过来，查到名字设置进去
        Destination dest = destinationService.getDeepNmaeById(strategyCatalog.getDestId());
        strategyCatalog.setDestName(dest.getName());

        //使用save方法是全量更新，如果更新部分，会出现未更新的字段被null覆盖
        //repository.save(strategyCatalog);
        //方案一：查询————替代————保存（效率低，用update）
        //方案二：显示使用update逻辑 update set...
        //条件对象
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(strategyCatalog.getId()));

        //使用工具简化更新的代码
        DBHelper.update(template, query, strategyCatalog, "destId", "destName", "state", "name", "sequence");

    }

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        //目的地的name是null，倒是前台传了destId过来，查到名字设置进去
        Destination dest = destinationService.getDeepNmaeById(strategyCatalog.getDestId());
        strategyCatalog.setDestName(dest.getName());

        repository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    //拼数据结构：用于显示攻略分类的层次级别
    @Override
    public List<CatalogVO> groupList() {
        List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
                //addToSet("name").as("names").//使用addToSet，无序的，name和id对不上，所以使用push
                //addToSet("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0; i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setMapList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    //通过目的地的id查询攻略的分类
    @Override
    public List<StrategyCatalog> queryByDestId(String destId) {
        List<StrategyCatalog> list = repository.findByDestId(destId);
        //攻略分类下的所有的攻略文章，只显示3条：limit 0, 3
        for (StrategyCatalog catalog : list) {
            List<Strategy> strategies = strategyService.getByCatalogId(catalog.getId());
            catalog.setStrategies(strategies);
        }
        return list;
    }

}
